<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="height:96%; max-height:96%;overflow: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :default-expanded-keys="defaultExpandedKeys"
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              highlight-current
              v-loading="treeLoading"
              show-checkbox
              @check="onCheck"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <!--                <div style="vertical-align: -0.15em;margin-right: 5px; display: block;">-->
                  <!--                                   <el-icon-folder-checked  style="height: 1.1em;width: 1.1em" />-->
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>

                  <!--                <i class="el-icon-menu" v-if="data.deviceType == 1" ></i>-->
                  <!--                <i class="el-icon-s-grid" v-if="data.deviceType == 2" ></i>-->
                  <!--                </div>-->
                  <span>{{ node.label }}</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" size="mini" v-show="showSearch" label-width="70px">
              <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                <el-form-item label="用量" size="mini">
                  <el-col :span="10">
                    <el-input size="mini" style="width: 98px;" placeholder="起始值"
                              v-model="queryParams.usageMin">
                      <template slot="suffix">
                        <div>m³</div>
                      </template>
                    </el-input>
                  </el-col>
                  <el-col class="line" :span="4" style="text-align: center">至</el-col>
                  <el-col :span="10">
                    <el-input size="mini" style="width: 98px;" placeholder="结束值"
                              v-model="queryParams.usageMax">
                      <template slot="suffix">
                        <div>m³</div>
                      </template>
                    </el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="时间">
                  <el-date-picker
                    v-model="time"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :picker-options="pickerOptions"
                    @change="handleDateChange"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini" v-has-permi="['datastatistics:terminalsfreezexb:listUsage']">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
            <el-button type="primary" icon="el-icon-download" size="mini" style="margin-left: 20px;"
                       @click="handleExport" v-has-permi="['datastatistics:terminalsfreezexb:exportUsage']">导出
            </el-button>
          </el-col>
        </el-row>
        <div style="margin-top: 5px;">
          <el-row style="margin-top: 10px;">
            <el-table size="mini" border :height="getAvailableHeight" :data="waterConsumptionData"
                      style="width: 100%" v-loading="tableLoading" :default-sort="defaultSort" :span-method="objectSpanMethod"
                      @sort-change="handleSorterChange">
              <el-table-column type="index" label="#" width="40" align="center"/>
              <el-table-column prop="sheetsName" label="所属区域" align="center" :sort-orders="['ascending','descending']" sortable="custom"/>
              <el-table-column prop="date" label="时间" align="center" :sort-orders="['ascending','descending']" sortable="custom"/>
              <el-table-column prop="userId" label="用户编号" align="center" :sort-orders="['ascending','descending']" sortable="custom"/>
              <el-table-column prop="userName" label="用户名称" align="center" :sort-orders="['ascending','descending']" sortable="custom"/>
              <el-table-column prop="terminalId" label="设备编号" align="center" :sort-orders="['ascending','descending']" sortable="custom"/>
              <el-table-column prop="installAddress" label="安装地址" align="center"/>
              <el-table-column prop="usage" label="用水量(m³)" align="center" sortable="custom"
                               :sort-orders="['ascending','descending']"/>
              <el-table-column prop="totalUsage" label="区域用水量(m³)" align="center" />
            </el-table>
          </el-row>

          <pagination
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import moment from "moment";
import {getTerminalSheetsUsage} from "../../../api/analysis/meter/areaDayWaterDosage";

export  default {
  name: 'DayWaterDosage',
  data() {
    return {
      pickerOptions: {
        onPick: ({ minDate }) => {
          this.beginDate = minDate;
        },
        disabledDate: (time) => {
          return this.disabledDate(time)
        },
      },
      fold: false,
      collapseAble: false,
      // 显示搜索条件
      showSearch: true,
      columnObj: {},
      columnArr: ['sheetsName', 'totalUsage'],
      defaultExpandedKeys: [],
      screenHeight: null,
      treeLoading: false,
      tableLoading: false,
      // 默认排序
      defaultSort: {prop: 'usage', order: 'descending'},
      // 区域树选项
      sheetsTreeList: [],
      waterConsumptionData: [],
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsIds: null,
        beginDate: new moment().subtract(7, 'day').format('YYYY-MM-DD'),
        endDate: new moment().subtract(1, 'day').format('YYYY-MM-DD'),
        usageMin: null,
        usageMax: null,
        toUnderScore: false
      },
      filterText: '',
      time: [
        new moment().subtract(7, 'days').format('YYYY-MM-DD'),
        new moment().subtract(1, 'days').format('YYYY-MM-DD')
      ]
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 225
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  mounted() {
    // this.tip();
    this.getTreeList()
    this.handleCheck()
  },
  methods: {
    // 区域树勾选数据时触发
    onCheck(node, data){
      this.queryParams.sheetsIds = this.$refs.tree.getCheckedKeys().join(',')
      this.handleQuery()
    },
    // 日期选择框改变事件
    handleDateChange(e) {
      this.queryParams.beginDate = e[0]
      this.queryParams.endDate = e[1]
    },
    // 时间选择器禁用
    disabledDate(time) {
      if(this.beginDate){
        // 计算第一个日期前后十五天的范围
        const minDate = moment(this.beginDate).subtract(15, 'days');
        const maxDate = moment(this.beginDate).add(15, 'days');
        // 检查当前日期是否在允许的范围内
        return moment(time).isBefore(minDate) || moment(time).isAfter(maxDate);
      } else {
        return false;
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    getSpanArr(data) {
      // this.columnArr.forEach((key, index) => {
      //
      //   console.log(this.columnObj,"this.columnObj")
      // })
      let count = 0
      this.columnObj.sheetsName = []
      this.columnObj.totalUsage = []
      data.forEach((item, index) => {
        if(index === 0){
          this.columnObj.sheetsName.push(1)
        }else {
          // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
          if (item.sheetsName === data[index - 1].sheetsName) {
            this.columnObj.sheetsName[count] += 1;
            this.columnObj.sheetsName.push(0);
          } else {
            // 如果当前行和上一行其值不相等
            count = index; // 记录当前位置
            this.columnObj.sheetsName.push(1); // 重新push 一个 1
          }
        }
      })
      this.columnObj.totalUsage = this.columnObj.sheetsName
    },
    // 合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 判断列的属性
      if(this.columnArr.indexOf(column.property) !== -1) {
        // 判断其值是不是为0
        if(this.columnObj[column.property][rowIndex]) {
          return [this.columnObj[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
// 页面提示信息
    tip() {
      this.$modal.msgWarning("请选择区域查看数据!")
    },
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage'
      switch (prop){
        case 'usage':
          this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage'
          break;
        case 'terminalId':
          this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage,xb.terminal_id'
          break;
        case 'userId':
          this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage,xb.user_id'
          break;
        case 'date':
          this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage,ttfx.freeze_time'
          break;
        case 'userName':
          this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage,UX.user_name'
          break;
      }
      this.queryParams.isAsc = order
      this.handleQuery()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      let temp_ = ''
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = 's.sheets_code,ttfx.usage'
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
        this.treeLoading = false;
      }
    },
    // 判断是否为超级管理员 如果是 则初始化时不进行查询 否则默认勾选所有区域进行查询
    handleCheck() {
      this.checkedKeys = []
      if(this.systemFlag !== 0){
        this.setAllCheckedKeys()
      }
    },
    // 设置所有区域树节点key
    setAllCheckedKeys() {
      if(this.sheetsTreeList.length > 0){
        this.sheetsTreeList.forEach(node => {
          this.getAllNodeIds(node)
        })
        this.$refs.tree.setCheckedKeys(this.checkedKeys)
        this.$nextTick(() => {
          this.queryParams.sheetsIds = this.$refs.tree.getCheckedKeys().join(',')
          this.handleQuery()
        });
      }
    },
    /** 查询抄表率明细 */
    handleQuery() {
      this.checkSortColumn()
      if (this.queryParams.sheetsIds.length > 0) {
        this.tableLoading = true;
        getTerminalSheetsUsage(this.queryParams).then(response => {
          if (response.code === 200) {
            this.total = response.total;
            this.waterConsumptionData = response.rows
            this.getSpanArr(this.waterConsumptionData);
          }
          this.tableLoading = false;
        });
      }else {
        this.$modal.msgWarning("请选择区域查看数据!")
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/terminalsfreezexb/exportTerminalSheetsUsage', {
        ...this.queryParams
      }, `日用水量统计数据.xlsx`)
    },
    // 重置
    resetQuery(){
      this.time = [new moment().subtract(7, 'day').format('YYYY-MM-DD'),new moment().subtract(1, 'day').format('YYYY-MM-DD')],
        this.$refs.tree.setCheckedNodes([])
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        sheetsIds: null,
        beginDate: new moment().subtract(7, 'day').format('YYYY-MM-DD'),
        endDate: new moment().subtract(1, 'day').format('YYYY-MM-DD'),
        usageMin: null,
        usageMax: null,
        toUnderScore: false
      }
      this.handleQuery()
    },
  }
}
</script>
<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 25%;
  }
}

.form_query {
  width: 20%;
  text-align: right;
}
</style>
